package cn.jltx.mvpdemopro.presenter;

import android.os.Handler;
import android.os.Looper;

import cn.jltx.mvpdemopro.config.ErroCode;
import cn.jltx.mvpdemopro.model.User;
import cn.jltx.mvpdemopro.view.ILoginView;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2016/04/06.
 */

public class LoginPresenterImp extends BaseLoginPresenter<ILoginView>{
    User user;
    Handler handler;

    public LoginPresenterImp() {
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void login(final String name, final String password) {
        new Thread(){
            @Override
            public void run() {
                try
                {
                    Thread.sleep(2000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }

                int check = user.checkUserValidity(name,password);
                if(check > 0){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            mView.onSuccess(user);
                        }
                    });
                }else if(check == 0){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            mView.onFailure(ErroCode.LOGIN_PASSWORD_ERROR);
                        }
                    });
                }else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            mView.onFailure(ErroCode.LOGIN_USER_ERROR);
                        }
                    });
                }
            }
        }.start();
    }

    @Override
    public void attach(ILoginView mView) {
        super.attach(mView);
        initUser();
    }

    @Override
    public void clear() {
        mView.onClearText();
    }

    private void initUser(){
        user = new User("jltx","1123");
        mView.initUser(user.toString());
    }

    @Override
    public String getUsername() {
        if(user != null){
            return user.getUsername();
        }
        return null;
    }

    @Override
    public void setUsername(String username) {
        if(user != null){
            user.setUsername(username);
        }
    }

    @Override
    public String getPassword() {
        if(user != null){
            user.getPassword();
        }
        return null;
    }

    @Override
    public void setPassword(String password) {
        if(user != null){
            user.setPassword(password);
        }
    }
}
